package home.project.misc;

import home.project.misc.Rect.Circle;
import openfl.geom.Rectangle;
import openfl.geom.Point;

/**
 * ...
 * @author an.vuongngocduy
 */

class Rect extends Rectangle {
	public var target(default, null):Entity;
	
	public function new(p_target:Entity, p_x:Float, p_y:Float, p_width:Float, p_height:Float) {
		super(p_x, p_y, p_width, p_height);
		target = p_target;
	}
	
	public override function intersects(toIntersect:Rectangle):Bool {
		if (Std.is(toIntersect, Circle)) {
			var toIntersectCircle:Circle = cast(toIntersect, Circle);
			return toIntersectCircle.intersects(toIntersect);
		}
		else if (Std.is(toIntersect, Rect)) {
			var r:Rect = cast(toIntersect, Rect);
			
			var left1:Float = target.absoluteTransform.tx + super.left;
			var top1:Float = target.absoluteTransform.ty + super.top;
			var right1:Float = target.absoluteTransform.tx + super.right;
			var bottom1:Float = target.absoluteTransform.ty + super.bottom;
						
			var left2:Float = r.target.absoluteTransform.tx + r.left;
			var top2:Float = r.target.absoluteTransform.ty + r.top;
			var right2:Float = r.target.absoluteTransform.tx + r.right;
			var bottom2:Float = r.target.absoluteTransform.ty + r.bottom;
			
			return (left1 <= left2 && right1 >= left2 &&  top1 <= top2 && bottom1 >= top2)
				|| (left1 <= left2 && right1 >= left2 &&  top1 <= bottom2 && bottom1 >= bottom2)
				|| (left1 <= right2 && right1 >= right2 &&  top1 <= top2 && bottom1 >= top2)
				|| (left1 <= right2 && right1 >= right2 &&  top1 <= bottom2 && bottom1 >= bottom2);
		}
		else {
			return super.intersects(toIntersect);
		}
	}
}

class Circle extends Rect {
	
	public var radius(default, default):Float;
	
	public var center(default, default):Point;
	
	public function new(p_target:Entity, p_cx:Float, p_cy:Float, p_radius:Float) {
		super(p_target, p_cx - p_radius, p_cy - p_radius, p_radius * 2, p_radius * 2);
		radius = p_radius;
		center = new Point(p_cx, p_cy);
	}
	
	public override function containsPoint(point:Point):Bool {
		return radius >= center.subtract(point).length;
	}
	
	public override function intersects(toIntersect:Rectangle):Bool {
		if (Std.is(toIntersect, Circle)) {
			var toIntersectCircle:Circle = cast(toIntersect, Circle);
			return (radius + toIntersectCircle.radius) >= center.subtract(toIntersectCircle.center).length;
		}
		else {
			return false;
		}
	}
}


